﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;
using System.IO.Compression;
using System.Text;
using GZipInteractJS.Dto;

namespace GZipInteractJS.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UploadController : ControllerBase
    {
        /// <summary>
        /// 上传压缩数据
        /// </summary>
        [HttpPost]
        [Route("UploadCompressedData")]
        public async Task<IActionResult> UploadCompressedData([FromForm] BlobUploadDto input)
        {
            if (input.BlobData == null || input.BlobData.Length == 0)
            {
                return BadRequest("No compressed data provided.");
            }

            using var compressedStream = input.BlobData.OpenReadStream();
            byte[] decompressedData = await GZipHelper.Decompress(compressedStream);

            string contentString = Encoding.UTF8.GetString(decompressedData);

            return Ok(new { input.BusinessType, content = contentString });
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        [HttpPost]
        [Route("UploadFile")]
        public async Task<IActionResult> UploadFile([FromForm] FileUploadDto input)
        {
            if (input.File == null || input.File.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads", input.File.FileName);
            if (!Path.Exists(filePath))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
            }

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await input.File.CopyToAsync(stream);
            }

            return Ok(new { input.BusinessType, input.File.FileName });
        }
    }
}
